// import { showError } from '../index'
// import { Base64 } from '../base64'

// export const BASE_URL = 'http://localhost:8888/news/'
export const BASE_URL = 'http://193.112.31.116:8888/news/'
let ERROR_COUNT = 0

export const request = (url, data, option) => {

	console.log("url:  "+url);
	console.log("data: "+JSON.stringify(data));
  if (option && option.loading) {
//     wx.showLoading({
//       title: '数据加载中!',
//       mask: true
//     })
  }
  return new Promise((resolve, reject) => {
    uni.request({
      url: BASE_URL + url,
      data: data,
      method: (option && option.method) || 'post',
      header: {
        'Content-Type': (option && option.contentType) || 'application/json',
        'Mini-Token': uni.getStorageSync('MY_TOKEN')
      },
      success: (res) => {
		  console.log('res:' + JSON.stringify(res))
        ERROR_COUNT = 0
        if (res.data.code == '2013') {
          getToken(request, url, data, option).then((response) => {
            console.log('正真的返回值:')
            resolve(response)
          })
        } else if (res.data.code == '0000') {
          resolve(res)
        } else {
			     console.log(res)
					 uni.showToast({
					
					 	title:res.data.msg
					 })
					// uni.hideLoading();
          // showError(res.data.msg)
          // resolve(res)
        }
        if (option && option.loading) {
         	uni.hideLoading();
        }
      },
      fail: (err) => {
        ERROR_COUNT += 1
        if (ERROR_COUNT == 3) {
          if (option && option.loading) {
            	uni.hideLoading();
          }
         	uni.showToast({
         	title: "系统错误"
         })
          reject(err)
        } else {
          request(url, data, option)
        }
      }
    })
  })
}

export const getToken = (callback, url, data, option) => {
	console.log("开始登陆");
  return new Promise((resolve, reject) => {
    uni.login({
      success: function (res) {
		  let type = '';
		  console.log("res:  "+JSON.stringify(res))
		  // #ifdef MP-WEIXIN
		  type = "weixin"
		  // #endif
		  // #ifdef MP-ALIPAY
		   type = "zhifubao"
		  // #endif
		  
	 	// #ifdef MP-TOUTIAO
	 	  type = "toutiao"
       // #endif
        if (res.code) {
          console.log('----token失效，重新获取token----')
          console.log("res:  "+res.code)
          request('member/loginByApp', {jsCode: res.code,type: type}).then((response) => {
			  console.log('获取TOKEN后的返回值1:'+JSON.stringify(response)) 
            uni.setStorageSync('MY_TOKEN', response.data.data.token)
            callback(url, data, option).then((resp) => {
              console.log('获取TOKEN后的返回值:')
              console.log(resp)
              resolve(resp)
            })
          }).catch((err) => {
            console.log(err)
          })
        }
      }
    })
  })
}

